//
//  MYRefreshControl.m
//  MYChatting
//
//  Created by mac on 16/8/26.
//  Copyright © 2016年 lhf. All rights reserved.
//

#import "MYRefreshControl.h"
#import "Masonry.h"

typedef enum : NSUInteger {
    Normal,
    Pulling,
    Refreshing,
} MYRefreshState;

#define RefreshViewHeight 60


@interface MYRefreshControl ()

@property (nonatomic,weak) UILabel *tipLabel;
@property (nonatomic,weak) UIImageView *arrowIcon;
@property (nonatomic,weak) UIActivityIndicatorView *loadIcon;

@property (nonatomic,weak) UIScrollView *fatherView;

@property (nonatomic,assign) MYRefreshState refreshState;//标记状态

@property (nonatomic,assign) MYRefreshState oldState;
@end

@implementation MYRefreshControl

- (void)setRefreshState:(MYRefreshState)refreshState{
    _refreshState = refreshState;
    
      if(refreshState == Pulling) {
            self.tipLabel.text = @"准备起飞";
            [UIView animateWithDuration:0.25 animations:^{
                self.arrowIcon.transform = CGAffineTransformMakeRotation(M_PI);
            }];
      }else if (refreshState == Refreshing){
            self.tipLabel.text = @"正在起飞";
            self.arrowIcon.hidden = YES;
            [self.loadIcon startAnimating];
          //设置动画只是为了让加载圈看的更清楚 没有这个动画 只要实现sendActionsForControlEvents就可以实现UIControl的target方法
            [UIView animateWithDuration:0.25 animations:^{
                UIEdgeInsets inset = self.fatherView.contentInset;
                inset.top += RefreshViewHeight;
                self.fatherView.contentInset = inset;
            }];
#warning 触发control事件  必须写，否则UIControl的target方法无效
            [self sendActionsForControlEvents:UIControlEventValueChanged];
      }else if (refreshState == Normal){
            self.tipLabel.text = @"下拉起飞";
            self.arrowIcon.hidden = NO;
            [self.loadIcon stopAnimating];
          if (self.oldState == Refreshing) {
        
            [UIView animateWithDuration:0.25 animations:^{
                UIEdgeInsets inset = self.fatherView.contentInset;
                inset.top -= RefreshViewHeight;
                self.fatherView.contentInset = inset;
            }];
          }
            [UIView animateWithDuration:0.25 animations:^{
                self.arrowIcon.transform = CGAffineTransformIdentity;
            }];
    }
    self.oldState= refreshState;
}

#warning view的生命周期方法
- (void)willMoveToSuperview:(nullable UIView *)newSuperview{
    [super willMoveToSuperview:newSuperview];
    
    //获取当前控件的父控件
    UIScrollView *fatherView = (UIScrollView *)newSuperview;
    self.fatherView = fatherView;
    
    //设置kvo观察者
    [self.fatherView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
}


//实现kvo方法
- (void)observeValueForKeyPath:(nullable NSString *)keyPath ofObject:(nullable id)object change:(nullable NSDictionary<NSString *,id> *)change context:(nullable void *)context{
    //临界值
    CGFloat insetTop = self.fatherView.contentInset.top;
    CGFloat condationValue = - (RefreshViewHeight + insetTop);
    //
    CGFloat offsetY = self.fatherView.contentOffset.y;
    
    if (self.fatherView.dragging) {
        if (self.refreshState == Normal && offsetY < condationValue) {
            //下拉到临界值 没松手刷新
            self.refreshState = Pulling;
            
        }else if (self.refreshState == Pulling && offsetY > condationValue){
            //进入默认状态
            self.refreshState = Normal;
        }
    }else{
        // 不是在被拉拽的状态 并且 当前的视图的statue 是 pulling状态 再执行刷新操作
        if (self.refreshState == Pulling) {
            self.refreshState = Refreshing;
        }
    }
}

- (void)endRefreshing{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.refreshState = Normal;
    });
    
}


//移除kvo观察
- (void)dealloc{
    [self.fatherView removeObserver:self forKeyPath:@"contentOffset"];
}


- (instancetype)initWithFrame:(CGRect)frame
{
    //设置位置frame
    CGRect rect = CGRectMake(0, - RefreshViewHeight, kScreenWidth, RefreshViewHeight);
    self = [super initWithFrame:rect];
    if (self) {
        self.oldState = Normal;
        self.backgroundColor = [self randomColor];
        [self setUpUI];
    }
    return self;
}


- (void)setUpUI{
    UILabel *tipLabel = [[UILabel alloc] init];
    tipLabel.text = @"下拉刷新";
    tipLabel.textColor = [self randomColor];
    tipLabel.font = [UIFont systemFontOfSize:14];
    [self addSubview:tipLabel];
    self.tipLabel  = tipLabel;
    
    UIImageView *arrowIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tableview_pull_refresh"]];
    [self addSubview:arrowIcon];
    [arrowIcon sizeToFit];
    self.arrowIcon = arrowIcon;
    
    UIActivityIndicatorView *loadIcon = [[UIActivityIndicatorView alloc] init];
    [self addSubview:loadIcon];
    self.loadIcon = loadIcon;
    
   [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
       make.centerX.equalTo(self.mas_centerX).offset(15);
       make.centerY.equalTo(self.mas_centerY);
   }];
    
    [arrowIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(tipLabel.mas_left).offset(-5);
        make.centerY.equalTo(tipLabel.mas_centerY);
    }];
    
    [loadIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(arrowIcon);
    }];
}

- (UIColor *)randomColor{
    CGFloat red = arc4random_uniform(256.0) / 255.0;
    CGFloat blue = arc4random_uniform(256.0) / 255.0;
    CGFloat green = arc4random_uniform(256.0) / 255.0;
    return [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
}

@end
